<?php session_start() ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Admin</title>
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
	
<?php
require_once 'header.php';
require 'connect.php';

$status = '';
?>

<!-- This will take all city names from current DB and add them to 
 search list tags in html via PHP. After that, depending on selected city, related suburbs are going to be put from DB inside drop check list.
 So customer will only be able to choose from what data actualiy in DB.
 This prevents typos and unneccessery search requests. -->


<div id="search-wrapper">
<div>
    <h1>Admin Area</h1>
</div>
	<div id="search-form" class='container'>
		<div class="row">
					<div id="card-header">
                        <div>property_data</div>
						<h1 id="form-se-head">PROPERTY AND USERS SEARCH</h1>
					</div>
					<div class="card-body">
						<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
							<div class="form-row">
								<div class="form-group col">
									<select class="form-control" id="city" name="city">
										<option>SELECT CITY</option>
										<!-- adding all distinct cities from DB to search list -->
										<?php 
										$result = mysqli_query($conn,"SELECT DISTINCT city from addresses  ORDER BY city ASC");
										if ($result->num_rows > 0){
											while($property_data = mysqli_fetch_array($result)){ 
										?>
										<option value="<?php echo $property_data['city'];?>"><?php echo $property_data['city'];?></option>
										<?php
											}
										} else {$query_error = 'some error getting city data';}
										?>
									</select>
								</div>

								<div class="col">
									<!-- this dropdown populates from first one with 
											help of AJAX script above divs and suburb_list.php -->
									<div class="dropdown input-group">
									<button class="btn btn-secondary dropdown-toggle btn-block" type="button" 
									data-toggle="dropdown">
									SELECT SUBURB
									</button>
									<div class="dropdown-menu">
									<button class="dropdown-item" type="button" id="suburb">
									<option>no suburb detected</option>
									</button>
									</div>
									</div>
								</div>	

							</div>
							<div class=" form-row">
								<div class=" col">
									<select class="form-control" name='price'>
										<option>Price</option>
										<option value="150000">$150K+</option>
										<option value="300000">$300K+</option>
										<option value="600000">$600K+</option>
										<option value="1000000">$1M+</option>
									</select>
								</div>
								<div class=" col">
									<select class="form-control" name='bedrooms'>
										<option>Bedrooms</option>
										<option value="0">Any</option>
										<option value="1">1+</option>
										<option value="2">2+</option>
										<option value="3">3+</option>
									</select>
								</div>
							</div>
							<br>
							
							<div class="col">

									<!-- <this dropdown shows all users -->
									<div class="dropdown input-group">
									<button class="btn btn-secondary dropdown-toggle btn-block" type="button" 
									data-toggle="dropdown">
									SELECT USERS
									</button>

									<div class="dropdown-menu">
										<!-- adding all distinct USERs from DB to search list -->
										<?php 
										$result = mysqli_query($conn,"SELECT login from users");
										if ($result->num_rows > 0){
											while($user_data = mysqli_fetch_array($result)){ 
										?>
									<button class="dropdown-item" type="button" id="users">
									<input type="checkbox" name="users[]" value="<?php echo $user_data['login'];?>"><?php echo ' '.$user_data['login'];?>
									</button>
									<?php
											}
										} else {$query_error = 'some error getting user data';}
										?>
									</div>
									</div>
							</div>

							<div class="form-group text-center">
									<input id="sub-btn-search" type="submit" name="submit" class="btn-max btn-size" value="Submit" id="submit_search">
							</div>
						</form>
					</div>
		</div>
	</div>
</div>

<div class="search-results">
<?php

if( isset($_POST['submit'])){
// print_r($_POST); /////displaying for debuging purposes only
$sql = "";
  
	if( !empty($_POST['city'])){

		$city = $_POST['city'];

		$sql = "SELECT bedrooms, price, description, suburb, city, street_name, street_number,  properties.id, users.login FROM properties
		INNER JOIN addresses ON addresses.property_id = properties.id
        INNER JOIN users ON users.id = properties.user_id
		WHERE city = '".$city."'";

					// echo $sql, "<br>";/////displaying for debuging purposes only
					// echo	print_r($_POST['suburbs']);/////displaying for debuging purposes only
		$current_user = $_SESSION['user_id'];

		if( !empty($_POST['suburbs'])){


			$suburbs_names = "";

			foreach($_POST['suburbs'] as $value){

				if (empty($suburbs_names)){

					$suburbs_names = "'".$value."'"; 
				}
				else{ $suburbs_names = $suburbs_names.", '.$value.'"; }

        }
        $sql = "SELECT bedrooms, price, description, suburb, city, street_name, street_number, properties.id, users.login FROM properties 
					INNER JOIN addresses ON addresses.property_id = properties.id
                    INNER JOIN users ON users.id = properties.user_id
					WHERE addresses.suburb IN (".$suburbs_names.")";

					// echo  $sql, "<br>"; ////displaying for debuging purposes only
		}

		if(!($_POST['price'] === 'Price')){
			$price = $_POST['price'];
			$sql = $sql." AND price > ".$price;
		}
		if (!($_POST['bedrooms'] === 'Bedrooms')){
			$bedrooms = $_POST['bedrooms'];
			$sql = $sql." AND bedrooms > ".$bedrooms;
		}

		// echo $sql;/////displaying for debuging purposes only

		$result = mysqli_query($conn, $sql);
			 
			//echo print_r ($result);

		if (mysqli_num_rows($result) > 0){
			while($property_data = mysqli_fetch_assoc($result)){
				
				// echo print_r($property_data), "<br>";////displaying for debuging purposes only -->
				
				//getting photos urls or current property

				$sql = "SELECT property_id FROM featuredlists WHERE property_id = $property_data[id]";
				$result_featured_list = mysqli_query($conn, $sql);

				if (mysqli_num_rows($result_featured_list) ==  0 ) {
					$featured_list_state = "Tag as Featured";
					$btn_color = "add-to-wishlist-btn";
				}
				else {
					$featured_list_state = "Remove from Featured";
					$btn_color = "add-to-wishlist-btn-toggle add-to-wishlist-btn";
				}

				$sql = "SELECT photo_url FROM photos WHERE property_id = $property_data[id]";
				$result_photos = mysqli_query($conn, $sql);

				if (mysqli_num_rows($result_photos) > 0){ ?>

				<div>
					<?php $current_property_photo_urls = mysqli_fetch_assoc($result_photos);
					//echo ($current_property_photo_urls['photo_url']);////displaying for debuging purposes only
					$photoUrl = './'.$current_property_photo_urls['photo_url'];
					?>
				</div>


			<?php
				}
			}
		} else {$status = "City has to be selected.";}
	}
}
}
?>

<script type="text/javascript">
   $(document).ready(function(){
   	// City dependent ajax
   	$("#city").on("change",function(){
   	var city_selected = this.value;
    $.ajax({
		url: "suburb_list.php",
		type: "POST",
		cache:false,
		data:{ city_selected: city_selected },
  		success:function(result){
      	$("#suburb").html(result);
  		}
    });	
  });
});
</script>

<script type="text/javascript">

function AddFeatured(data){
	var link_data = data;
	   console.log('Link_data:'+link_data);
       $.ajax({
          type: "POST",
          url: 'addtofeatured.php',
          cache:false,
          data: { link_data: link_data },
          	success:function(result){
				  console.log("AJ success"+result);
               if(result == 1)
               {
                   $('a[data="' + link_data + '"]').addClass("add-to-wishlist-btn-toggle").text("Remove from Featured");
               }
               else{
                   $('a[data="' + link_data + '"]').removeClass("add-to-wishlist-btn-toggle").text("Tag as Featured");
               }
          },
		  error:function(result){
			console.log("AJ error");
		  }
       });   
}
</script>

<script type="text/javascript">

function deleteP(id){
	var delete_p_id = id;
	   console.log('delete_p_id:'+delete_p_id);
       $.ajax({
          type: "POST",
          url: 'delete-property.php',
          cache:false,
          data: { delete_p_id: delete_p_id },
          	success:function(result_delete){
				  console.log("AJ delete success "+result_delete);
                  if(result_delete == 1)
               {
                   console.log ("deleted-changed-txt")
                   $('a[id="' + delete_p_id + '"]').addClass("removed-property-btn removed-property-btn-wrapper").removeClass("remove-prop-btn").text("Property Deleted");
                   $('a[data="' + delete_p_id + '"]').addClass("dis-none");

               }
               else{
                    console.log ("deleted-unchanged-txt")
                   $('a[id="' + delete_p_id + '"]').removeClass("add-to-wishlist-btn-toggle");
               }
          },
		  error:function(result_delete){
			console.log("AJ delete error");

		  }
       });   
    }
</script>

</div>
</body>
</html>